package api

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"

	"laravel-vue-admin/socket/hub"
	"laravel-vue-admin/socket/message"
)

// API 提供HTTP API接口供Laravel后端调用
type API struct {
	hub *hub.Hub
}

// NewAPI 创建新的API服务
func NewAPI(h *hub.Hub) *API {
	return &API{hub: h}
}

// SendMessageRequest 发送消息请求
type SendMessageRequest struct {
	Type      string      `json:"type"`       // broadcast, user, room
	ToUserID  int64       `json:"to_user_id,omitempty"`
	ToUserIDs []int64     `json:"to_user_ids,omitempty"`
	RoomID    string      `json:"room_id,omitempty"`
	Action    string      `json:"action"`     // chat, notify, system
	Content   interface{} `json:"content"`
	Data      interface{} `json:"data,omitempty"`
}

// SendMessage 发送消息接口
func (a *API) SendMessage(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPost {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	// 读取请求体
	body, err := io.ReadAll(r.Body)
	if err != nil {
		http.Error(w, "读取请求体失败", http.StatusBadRequest)
		return
	}
	defer r.Body.Close()

	var req SendMessageRequest
	if err := json.Unmarshal(body, &req); err != nil {
		http.Error(w, "解析请求失败", http.StatusBadRequest)
		return
	}

	// 创建消息
	msg := &message.Message{
		Type:    req.Type,
		Action:  req.Action,
		ToUserID: req.ToUserID,
		RoomID:  req.RoomID,
		Content: req.Content,
		Data:    req.Data,
	}

	// 发送消息
	switch req.Type {
	case "broadcast":
		a.hub.Broadcast(msg)
	case "user":
		if req.ToUserID > 0 {
			a.hub.SendToUser(req.ToUserID, msg)
		} else if len(req.ToUserIDs) > 0 {
			a.hub.SendToUsers(req.ToUserIDs, msg)
		} else {
			http.Error(w, "缺少to_user_id或to_user_ids", http.StatusBadRequest)
			return
		}
	case "room":
		// TODO: 实现房间功能
		http.Error(w, "房间功能暂未实现", http.StatusNotImplemented)
		return
	default:
		http.Error(w, "不支持的消息类型", http.StatusBadRequest)
		return
	}

	// 返回成功响应
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"code":    200,
		"message": "消息发送成功",
	})
}

// GetOnlineUsers 获取在线用户列表
func (a *API) GetOnlineUsers(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	users := a.hub.GetOnlineUsers()
	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"code":    200,
		"message": "success",
		"data": map[string]interface{}{
			"online_users": len(users),
			"users":        users,
		},
	})
}

// IsUserOnline 检查用户是否在线
func (a *API) IsUserOnline(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodGet {
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
		return
	}

	userIDStr := r.URL.Query().Get("user_id")
	if userIDStr == "" {
		http.Error(w, "缺少user_id参数", http.StatusBadRequest)
		return
	}

	var userID int64
	if _, err := fmt.Sscanf(userIDStr, "%d", &userID); err != nil {
		http.Error(w, "无效的user_id", http.StatusBadRequest)
		return
	}

	isOnline := a.hub.IsUserOnline(userID)
	connections := a.hub.GetUserConnections(userID)

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusOK)
	json.NewEncoder(w).Encode(map[string]interface{}{
		"code":    200,
		"message": "success",
		"data": map[string]interface{}{
			"user_id":     userID,
			"is_online":   isOnline,
			"connections": connections,
		},
	})
}

// RegisterRoutes 注册路由
func (a *API) RegisterRoutes() {
	http.HandleFunc("/api/send", a.SendMessage)
	http.HandleFunc("/api/online-users", a.GetOnlineUsers)
	http.HandleFunc("/api/user-online", a.IsUserOnline)
}

